package com.community.sqlapp.controller;

import com.community.sqlapp.entity.TencentCosFile;
import com.community.sqlapp.mapper.TencentCosFileMapper;
import com.community.sqlapp.service.FileInfoService;
import com.community.sqlapp.service.QwenVlToXmindService;
import com.community.sqlapp.service.TestPointConverService;
import com.google.gson.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xmind.core.CoreException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class FileToTestPointController {

    @Autowired
    private QwenVlToXmindService qwenVlService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private TencentCosFileMapper tencentCosFileMapper;

    /**
     * 图片生成xmind测试点
     * @param file
     * @param promot
     * @return
     * @throws IOException
     * @throws CoreException
     */
    @PostMapping("/imageUpload")
    public Map<String, Object> imageUploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "promot", required = false) String promot) throws IOException, CoreException {
        Map<String, Object> response = new HashMap<>();
        try {
            // 2. 上传到腾讯云COS
            String fileUrl = fileInfoService.uploadCOSFile(file);
            System.out.println("fileUrl: "+fileUrl);
            // 3. 存入数据库
            TencentCosFile cosFile = new TencentCosFile();
            cosFile.setFileName(file.getOriginalFilename());
            cosFile.setFileUrl(fileUrl);
            tencentCosFileMapper.insert(cosFile);

            // 4. 用fileUrl调用大模型
            String promotInfo = "请严格以如下JSON格式返回，不要输出多余的解释或Markdown，返回json内容包含一级模块、二级模块、测试点、测试用例名称";
            String userPrompt = (promot != null && !promot.isEmpty() ? promot : "请根据上传的需求文档自动提取所有功能点并生成详细的测试点，要求结构化、分层级、覆盖全面。") + promotInfo;
            //调用 qwen-vl-plus 模型解析文档内容（新版API，文档+文本）
            String aiJson = qwenVlService.parseDocument(fileUrl, userPrompt);
            System.out.println("返回数据： " + aiJson);
            String xmindPath = null;
            try {
                // 1. 提取content字段
                JsonObject resp = JsonParser.parseString(aiJson).getAsJsonObject();
                if (resp.has("output")) {
                    resp = resp.getAsJsonObject("output");
                }
                String content = "";
                if (resp.has("choices")) {
                    JsonArray choices = resp.getAsJsonArray("choices");
                    if (choices.size() > 0) {
                        JsonObject msg = choices.get(0).getAsJsonObject();
                        if (msg.has("message")) {
                            JsonObject message = msg.getAsJsonObject("message");
                            if (message.has("content")) {
                                content = message.get("content").getAsString();
                            }
                        }
                    }
                }
                if (content.isEmpty()) {
                    response.put("success", false);
                    response.put("error", "AI返回内容无content字段，原始返回：" + aiJson);
                    return response;
                }
                // 2. 去除markdown代码块包裹
                content = content.replaceAll("(?s)```json|```", "").trim();
                System.out.println("提取的content内容：\n" + content);
                // 3. 平铺数组转树状结构
                String xmindJson = TestPointConverService.flatJsonToXmindTree(content);
                System.out.println("解析成功！生成的JSON结构：\n" + xmindJson);
                // 4. 生成XMind文件
                String suffix = file.getOriginalFilename();
                int index = suffix.indexOf('.');
                if (index != -1) { // 确保找到了点号
                    suffix = suffix.substring(0, index); // 获取第一个点号之前的部分
                }
                System.out.println("文件名称"+ suffix);
                xmindPath = suffix+".xmind";
                TestPointConverService.generateXMind(xmindJson, xmindPath);
                System.out.println("XMind文件生成成功：" + xmindPath);
                response.put("success", true);
                response.put("message", "XMind 文件已生成");
                response.put("downloadUrl", "/fileconfig/download?file="+xmindPath);
            } catch (Exception e) {
                System.err.println("解析失败：" + e.getMessage());
                e.printStackTrace();
                response.put("success", false);
                response.put("error", "解析失败：" + e.getMessage());
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
        }
        return response;
    }

    /**
     * 图片上传到腾讯COS
     * @param file
     * @return
     */
    @PostMapping("/uploadtest")
    public ResponseEntity<String> uploadTest(@RequestParam("file") MultipartFile file) {
        try {
            String url = String.valueOf(fileInfoService.uploadCOSFile(file));
            System.out.println("fileUrl: "+url);
            return ResponseEntity.ok(url);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件生成测试点，根据文件名从数据库获取fileid
     * @param fileName 文件名
     * @param promot 提示词
     * @return
     * @throws IOException
     * @throws CoreException
     */
    @PostMapping("/wordUpload")
    public Map<String, Object> wordUpload(@RequestParam("fileName") String fileName, @RequestParam(value = "promot", required = false) String promot) throws IOException, CoreException {
        Map<String, Object> response = new HashMap<>();
        try {
            String promotInfo="请严格以如下JSON格式返回，不要输出多余的解释或Markdown，返回json内容包含一级模块、二级模块、测试点、测试用例名称";
            String userPrompt = promot != null && !promot.isEmpty() ? promot+promotInfo : "请根据上传的需求文档自动提取所有功能点并生成详细的测试点，要求结构化、分层级、覆盖全面。"+promotInfo;

            // 调用 Qwen-long 模型解析文档内容（新版API，文档+文本）
            String aiJson = qwenVlService.parseLongDocument(fileName, userPrompt);
            System.out.println("返回数据： " + aiJson);
            String xmindPath = null;
            try {
                // 1. 提取content字段
                JsonObject resp = JsonParser.parseString(aiJson).getAsJsonObject();
                if (resp.has("output")) {
                    resp = resp.getAsJsonObject("output");
                }
                String content = "";
                if (resp.has("choices")) {
                    JsonArray choices = resp.getAsJsonArray("choices");
                    if (choices.size() > 0) {
                        JsonObject msg = choices.get(0).getAsJsonObject();
                        if (msg.has("message")) {
                            JsonObject message = msg.getAsJsonObject("message");
                            if (message.has("content")) {
                                content = message.get("content").getAsString();
                            }
                        }
                    }
                }
                if (content.isEmpty()) {
                    response.put("success", false);
                    response.put("error", "AI返回内容无content字段，原始返回：" + aiJson);
                    return response;
                }
                // 2. 去除markdown代码块包裹
                content = content.replaceAll("(?s)```json|```", "").trim();
                System.out.println("提取的content内容：\n" + content);
                // 3. 平铺数组转树状结构
                String xmindJson = TestPointConverService.flatJsonToXmindTree(content);
                System.out.println("解析成功！生成的JSON结构：\n" + xmindJson);
                // 4. 生成XMind文件
                xmindPath = fileName+".xmind";
                TestPointConverService.generateXMind(xmindJson, xmindPath);
                System.out.println("XMind文件生成成功：" + xmindPath);

                response.put("success", true);
                response.put("message", "XMind 文件已生成");
                response.put("downloadUrl", "/fileconfig/download?file="+xmindPath);
            } catch (Exception e) {
                System.err.println("解析失败：" + e.getMessage());
                e.printStackTrace();
                response.put("success", false);
                response.put("error", "解析失败：" + e.getMessage());
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
        }
        return response;
    }
}